package com.example.administrator.myapplication.Http;

import android.content.Context;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

/**
 * Created by Administrator on 2019/10/4 0004.
 */

public class CookieManger implements CookieJar {

    private final Map<String, ConcurrentHashMap<String, Cookie>> cookies = new HashMap<>();;
    protected String getCookieToken(Cookie cookie) {
        return cookie.name() + "@" + cookie.domain();
    }


    public List<Cookie> get(HttpUrl url) {
        ArrayList<Cookie> ret = new ArrayList<>();
        if (cookies.containsKey(url.host()))
            ret.addAll(cookies.get(url.host()).values());
        return ret;
    }
    @Override
    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
        if (cookies != null && cookies.size() > 0) {
            for (Cookie cookie : cookies) {
                String name = getCookieToken(cookie);
                //将cookies缓存到内存中 如果缓存过期 就重置此cookie
                if (!cookie.persistent()) {
                    if (!this.cookies.containsKey(url.host())) {
                        this.cookies.put(url.host(), new ConcurrentHashMap<String, Cookie>());
                    }
                    this.cookies.get(url.host()).put(name, cookie);
                } else {
                    if (this.cookies.containsKey(url.host())) {
                        this.cookies.get(url.host()).remove(name);
                    }
                }
            }
        }
    }

        @Override
        public List<Cookie> loadForRequest (HttpUrl url){
            return this.get(url);
        }

}
